<!--  -->
<template>
    <div class='editor-bg' ref="bg" @click="onBgclick" >
		<div class="bg-image">
			<img :src="bgImgUrl" alt="">
		</div>
		<div class="top-bar">
			<slot name="top">

			</slot>
		</div>
        <div class="editor-main" ref="editmain" :style="boxStyle">
			<div class="wrap-left" ref="wrapleft" slot="wrap-left"></div>
			<div class="editor-wrap" ref="editWrap" :style="{width:wrapStyle.width,height:wrapStyle.height,borderWidth:options.printBorder?'1px':'0'}">

				<div class="decorate" :style="decorateStyle"></div>
				<div class="preview-material" :style="materialStyle" ref="material" style="z-index:1"></div>

				<div class="preview-mask" ref="mask" :style="pasterStyle" style="z-index:5">
					<div class="paster-img" ref="image" :style="{
						left:pasterCurrentOffset.left+'px',
						top:pasterCurrentOffset.top+'px',
						width:pasterRect.width?pasterRect.width+'px':'100%',
						height:pasterRect.height?pasterRect.height+'px':'100%',
						transform:`rotate(${rotateAngle}deg) scaleX(${flip})`,
						backgroundImage:`url(${pasterUrl})`
					}"></div>

				</div>
				<div class="preview-material" :style="materialStyle2" style="z-index:5" ref="material2"></div>
				<div class="preview-material" :style="materialStyle3" style="z-index:5" ref="material3"></div>
				<div class="paster-border"
				role="paster"
				:class="{active:pasterActive}"
				ref="paster"
				style="z-index:5"
				v-show="showBorder"
				:style="{
					left:pasterCurrentOffset.left+'px',
					top:pasterCurrentOffset.top+'px',
					width:pasterRect.width?pasterRect.width+'px':'calc(100% - 20px)',
					height:pasterRect.height?pasterRect.height+'px':'100%',
					transform:`rotate(${rotateAngle}deg)`
				}"
				@mousedown="pasterTouchStart" @mousemove="pasterTouchMove" @mouseup="pasterTouchEnd"
				@touchstart="pasterTouchStart" @touchmove="pasterTouchMove" @touchend="pasterTouchEnd">
					<div class="paster-btn-rotate"
					role="paster"
					@mousedown="rotateTouchStart" @mousemove="rotateTouchMove" @mouseup="rotateTouchEnd"
					@touchstart.stop="rotateTouchStart" @touchmove.stop="rotateTouchMove" @touchend.stop="rotateTouchEnd"></div>
					<div class="paster-btn-flip" role="paster" @click="changeFlip"></div>
					<div class="paster-btn-file" role="paster" v-if="options.allowChangePoster">
						<input type="file" @change="changeImg" accept="image/*" role="paster"/>
					</div>
				</div>
			</div>
			<div class="wrap-right" ref="wrapright" slot="wrap-right"></div>
			<div class="loading-wrap" v-if="loading">
				<slot name="loading"></slot>
			</div>
        </div>
		<div class="bottom-bar">
			<slot name="bottom"></slot>
		</div>
    </div>
</template>

<script>

export default {
	name: "img-merge-editor",
	props:{
        options:{
            type:Object,
            default() {
                return {

                }
            }
        },
    },
    watch:{
        'options.materialUrl':{
            handler:function(val){
                this.materialStyle.backgroundImage=`url(${val})`
                this.initStyle()
            },
            immediate:true
        },
        'options.pasterImgUrl':{
            handler:function(val){
                this.pasterUrl=val
            },
            immediate:true
        },
        'options.maskImgUrl':{
            handler:function(val){
                this.maskImg=val
            },
            immediate:true
		},
		'options.bgImgUrl':{
            handler:function(val){
                this.bgImgUrl=val
            },
            immediate:true
        },
    },
    data() {
        return {
			bgImgUrl:'',//整个页面背景
			boxStyle:{//编辑区
				width:0,
				height:0,
			},
			wrapStyle:{ //画布
				width:0,
				height:0,
			},
			materialStyle:{//底图
				width:0,
				height:0,
				backgroundImage:null
			},
			materialStyle2:{//素材图
				width:0,
				height:0,
				backgroundImage:null
			},
			materialStyle3:{//遮罩图
				width:0,
				height:0,
				backgroundImage:null
			},
			pasterStyle:{//用户图
				width:0,
				height:0,
			},
			decorateStyle:{//装饰图

			},
            pasterUrl:'',
            //贴图当前定位
            pasterCurrentOffset:{
                left:0,
                top:0
            },
            //贴图当前世界坐标
            currentDis:{},
            //贴图当前大小
            pasterRect:{
                width:null,
                height:null
            },
            //贴图原始比例
            imgRatio:null,
            //贴图旋转角度
            rotateAngle:0,
            //镜像翻转
			flip:1,
			maskImg:null,
			showBorder:true,
			loading:false,
			pasterActive:true,
			firstRender:true,
        };
    },
    methods: {

    },
    created() {
		this.loading=true
    },
    mounted() {
		this.imgRatio=this.$refs.paster.clientWidth/this.$refs.paster.clientHeight

    },
    methods:{
		async initStyle(){
			var defaultOpt={

				bgImgUrl:'', //整体背景图片
				materialUrl:'',//底图
				materialUrl2:'',//镂空图
				shapeMask:'',//形状图
				coverUrl:'',//覆盖图 如手机外壳
				pasterImgUrl:'',//用户图
				decorateImg:'',//装饰图
				boxWidth:null, //编辑区域宽度
				boxHeight:null, //编辑区域高度
				autoResize:false,//缩放比贴图区更小时是否自动贴合大小
				allowChangePoster:true,//是否允许更改图片
				printBorder:false,//是否包围边框打印
				borderRatio:0,//包围边框打印时 边框宽度与正面图宽度的比例
				area:{ //贴图区域参数
					x:0,
					y:0,
					w:null,
					h:null,
				},
				history:null
				// history:{
				// 	x:0, //上一次x坐标
				// 	y:0, //上一次y坐标
				// 	w:200,//上一次图片宽
				// 	h:200,//上一次图片高
				// 	rotate:0,//上一次旋转角度
				//  flip:1,//镜像翻转
				// }
			}

			this._options={}
			Object.keys(defaultOpt).forEach(key=>{
				if(this.options[key]!==undefined){
					this._options[key]=this.options[key]
				}else{
					this._options[key]=defaultOpt[key]
				}
			})

			// this._options=Object.assign({},defaultOpt,this.options)

			var boxW=this._options.boxWidth||(document.body.clientWidth*0.85)
			var boxH=this._options.boxHeight||(document.body.clientWidth*0.85)
			console.log("编辑器配置：",this._options)
			this.boxStyle={
				width:boxW+'px',
				height:boxH+'px',
			}
			this.pasterImgSize=await this.getImgSize(this.checkImgCors(this._options.pasterImgUrl))
			var img=new Image()
			img.crossOrigin = "Anonymous";
			img.src=this.checkImgCors(this._options.materialUrl)
			img.onload=()=>{

				this.isHorizontal =img.width>img.height
				var ratio=img.width/img.height
				var h
				var w
				if(this.isHorizontal){
					h=this.$refs.editmain.clientWidth/ratio
					w=this.$refs.editmain.clientWidth
					this.materialStyle={
						height:h+'px',
						width:w+'px',
						// left:0
					}
				}else{
					h=this.$refs.editmain.clientHeight
					w=this.$refs.editmain.clientHeight*ratio

				}


				//处理编辑区左右两边slot元素
				w=w-this.$refs.wrapleft.clientWidth-this.$refs.wrapleft.clientWidth
				h=w/ratio
				this.materialStyle={
					height:h+'px',
					width:w+'px',
					// left:0
				}
				this.wrapStyle.height=h+'px'
				this.wrapStyle.width=w+'px'

				this.materialStyle.backgroundImage=`url(${this._options.materialUrl})`
				this.materialStyle2=Object.assign({},this.materialStyle)
				this.materialStyle2.backgroundImage=`url(${this._options.materialUrl2})`
				this.materialStyle3=Object.assign({},this.materialStyle)
				this.materialStyle3.backgroundImage=`url(${this._options.coverUrl})`
				this.pasterStyle=Object.assign({},this.materialStyle)

				delete this.pasterStyle.backgroundImage
				if(this._options.shapeMask){
					this.pasterStyle.maskImage=`url(${this._options.shapeMask})`
				}


				var scale=this._options.w/this._options.h



				this.$nextTick(()=>{
					this.originScale=this.$refs.editWrap.clientWidth/img.naturalWidth
					var parentImage=new Image()
					parentImage.crossOrigin = "Anonymous";
					if(this._options.materialUrl2){
						parentImage.src=this.checkImgCors(this._options.materialUrl2)
					}else{
						parentImage.src=this.checkImgCors(this._options.materialUrl)
					}
					parentImage.onload=()=>{
						this.materialScaleX=this.$refs.material2.clientWidth/parentImage.naturalWidth
						this.materialScaleY=this.$refs.material2.clientHeight/parentImage.naturalHeight
						this.resetPasterRect()


					}



				})

				//装饰图
				if(this._options.decorateImg){
					var decorate=new Image()
					decorate.crossOrigin = "Anonymous";
					decorate.src=this.checkImgCors(this._options.decorateImg)
					decorate.onload=()=>{
						var ratio=w/img.naturalWidth
						this.decorateStyle={
							height:(decorate.naturalHeight*ratio)+'px',
							width:(decorate.naturalWidth*ratio)+'px',
							backgroundImage:`url(${decorate.src})`,
						}
					}
				}else{
					this.decorateStyle={
						display:'none'
					}
				}

				//边框包围打印 改变底图大小
				if(this._options.printBorder){
					var mh=Number(this.materialStyle.height.replace('px',''))
					var mw=Number(this.materialStyle.width.replace('px',''))
					mh=mh+(mw*this._options.borderRatio*2)
					mw=mw+(mw*this._options.borderRatio*2)
					this.wrapStyle.height=mh+'px'
					this.wrapStyle.width=mw+'px'
					this.pasterStyle.height=mh+'px'
					this.pasterStyle.width=mw+'px'
				}

			}

		},
		loadHistory(){
			var wrapScale=this.$refs.editWrap.clientWidth/this._options.history.boxW

			this.pasterCurrentOffset.left=this._options.history.x*wrapScale
			this.pasterCurrentOffset.top=this._options.history.y*wrapScale
			this.pasterRect.width=this._options.history.w*wrapScale
			this.pasterRect.height=this._options.history.h*wrapScale
			this.rotateAngle=this._options.history.angle
			this.flip=this._options.history.flip

			this.loading=false

		},
		resetPasterRect(){
			var paster=new Image()
			paster.crossOrigin = "Anonymous";
			paster.src=this.checkImgCors(this.pasterUrl)
			paster.onload=()=>{
				var ratio=paster.naturalWidth/paster.naturalHeight
				var parentRect={
					w:this.$refs.material.clientWidth,
					h:this.$refs.material.clientHeight,
				}
				if(this._options.area.w&&this._options.area.h){
					parentRect={
						w:this._options.area.w*this.materialScaleX,
						h:this._options.area.h*this.materialScaleY,
					}
				}
				var parentRatio=parentRect.w/parentRect.h
				if(ratio>parentRatio){
					//高度对齐
					this.pasterRect.height=parentRect.h
					this.pasterRect.width=this.pasterRect.height*ratio
				}else{
					//宽度对齐
					this.pasterRect.width=parentRect.w
					this.pasterRect.height=this.pasterRect.width/ratio

				}


				if(this._options.history&&this.firstRender){
					this.loadHistory()
				}else{
					this.pasterCurrentOffset.left=-(this.pasterRect.width-this.$refs.editWrap.clientWidth)/2
					this.pasterCurrentOffset.top=-(this.pasterRect.height-this.$refs.editWrap.clientHeight)/2
					if(this._options.area.y){
						this.pasterCurrentOffset.top=this._options.area.y*this.materialScaleY-((this.pasterRect.height-this._options.area.h*this.materialScaleY)/2)
					}
					if(this._options.area.x){
						this.pasterCurrentOffset.left=this._options.area.x*this.materialScaleX-((this.pasterRect.width-this._options.area.w*this.materialScaleX)/2)
					}
				}

				this.loading=false

				this.firstRender=false
				this.$emit('on-ready')
			}
		},
        pasterTouchStart(e){
            // e.preventDefault()
			// e.stopPropagation()

			var target=e
			if(e.touches){
				target=e.touches[0]
			}
            this.isTouchStart=true
            this.currentDis = {
                x: target.pageX,
                y: target.pageY
            }
			//备份一个贴图尺寸
            this.copyPasterRect=Object.assign({},this.pasterRect)
            //备份一个贴图边距
            this.copyOffset=Object.assign({},this.pasterCurrentOffset)

			if(e.touches){
				this.onPinchStart(e)
			}

        },
        pasterTouchMove(e){
            e.preventDefault()
			e.stopPropagation()
			if(!this.pasterActive)return
            if(this.isTouchStart){
				var end = {}
				var event=e
				if(e.touches){
					event=e.touches[0]
				}
                end.x = event.pageX - this.currentDis.x
                end.y = event.pageY - this.currentDis.y
                this.pasterCurrentOffset.left=this.copyOffset.left+end.x
                this.pasterCurrentOffset.top=this.copyOffset.top+end.y
			}
			if(e.touches){
				this.onPinchMove(e)
			}

        },
        pasterTouchEnd(e){
			this.isTouchStart=false
			if(e.touches){
				this.onPinchEnd(e)
			}

        },
        rotateTouchStart(e){
			e.preventDefault()
            e.stopPropagation()
            // 开始出发旋转按钮（含拖动逻辑）
            this.isRotateStart=true
			var event= e
			if(e.touches){
				event=e.touches[0]
			}
            // 起始坐标
            this.rotateStartPos={
                x: event.pageX,
                y: event.pageY
            }
            //此时编辑框的中心坐标
            this.centerPos={
                x: this.$refs.paster.clientWidth / 2 + this.getElementToPageLeft(this.$refs.paster),
                y: this.$refs.paster.clientHeight / 2 + this.getElementToPageTop(this.$refs.paster)
            }
            //如果该页面是第一次进入 尚未初始化贴图编辑框尺寸 则初始化
            if(this.pasterRect.width==null&&this.pasterRect.height==null){
                this.pasterRect.width=this.$refs.paster.clientWidth
                this.pasterRect.height=this.$refs.paster.clientHeight
            }
            //备份一个贴图尺寸
            this.copyPasterRect=Object.assign({},this.pasterRect)
            //备份一个贴图边距
            this.copyOffset=Object.assign({},this.pasterCurrentOffset)
            //此时触摸落点与贴图中心点的直线距离
            this.startDistance=Math.sqrt(Math.pow(event.pageX-this.centerPos.x,2)+Math.pow(event.pageY-this.centerPos.y,2),2)

            //备份一个旋转角度
            this.copyRotateAngle=this.rotateAngle
        },
        rotateTouchMove(e){
			e.preventDefault()
			e.stopPropagation()
			if(!this.pasterActive)return
            if(this.isRotateStart){
                var event= e
				if(e.touches){
					event=e.touches[0]
				}
                /** 拖拽放大缩小逻辑 开始 */
                // 鼠标位移距离
                var moveDistance=Math.sqrt(Math.pow(event.pageX-this.centerPos.x,2)+Math.pow(event.pageY-this.centerPos.y,2),2)
                // 位移距离产生的位移比例
                var ratio=(this.startDistance+(moveDistance-this.startDistance))/this.startDistance

                // 根据位移比例重置编辑框大小和边距
                this.pasterRect.width=this.copyPasterRect.width*ratio
                this.pasterRect.height=this.copyPasterRect.height*ratio
                this.pasterCurrentOffset.left=this.copyOffset.left+(this.copyPasterRect.width-this.copyPasterRect.width*ratio)/2
                this.pasterCurrentOffset.top=this.copyOffset.top+(this.copyPasterRect.height-this.copyPasterRect.height*ratio)/2
                /** 拖拽放大缩小逻辑 结束 */



                /** 旋转逻辑 开始 */
                // 计算出旋转角度
                var AB = {};
                var AC = {};
                AB.X = (this.rotateStartPos.x - this.centerPos.x);
                AB.Y = (this.rotateStartPos.y - this.centerPos.y);
                AC.X = (event.pageX - this.centerPos.x);
                AC.Y = (event.pageY - this.centerPos.y); // 分别求出AB,AC的向量坐标表示
                var direct = (AB.X * AC.Y) - (AB.Y * AC.X); // AB与AC叉乘求出逆时针还是顺时针旋转
                var lengthAB = Math.sqrt(Math.pow(this.centerPos.x - this.rotateStartPos.x, 2) +
                    Math.pow(this.centerPos.y - this.rotateStartPos.y, 2)),
                lengthAC = Math.sqrt(Math.pow(this.centerPos.x - event.pageX, 2) +
                    Math.pow(this.centerPos.y - event.pageY, 2)),
                lengthBC = Math.sqrt(Math.pow(this.rotateStartPos.x - event.pageX, 2) +
                    Math.pow(this.rotateStartPos.y - event.pageY, 2));
                var cosA = (Math.pow(lengthAB, 2) + Math.pow(lengthAC, 2) - Math.pow(lengthBC, 2)) /
                (2 * lengthAB * lengthAC); //   余弦定理求出旋转角
                var angle = Math.round(Math.acos(cosA) * 180 / Math.PI);
                if (direct < 0) {
                    this.rotateAngle = this.copyRotateAngle-angle; //叉乘结果为负表示逆时针旋转， 逆时针旋转减度数
                } else {
                    this.rotateAngle = this.copyRotateAngle+angle; //叉乘结果为正表示顺时针旋转，顺时针旋转加度数
                }
                /** 旋转逻辑 结束 */
            }
        },
        rotateTouchEnd(e){
			this.isRotateStart=false
			if(this._options.autoResize){
				this.checkResize()
			}

		},
		onPinchStart(e){
			if(e.touches.length>=2){
				this.isPinch=true
				this.startTouches=e.touches
				this.copyRotateAngle=this.rotateAngle
			}
		},
		onPinchMove(e){
			if(!this.pasterActive)return
			if(e.touches.length>=2&&this.isPinch){
				var now=e.touches; //得到第二组两个点
				var scale=this.getDistance(now[0],now[1])/this.getDistance(this.startTouches[0],this.startTouches[1]); //得到缩放比例，getDistance是勾股定理的一个方法
				var rotation=this.getAngle(now[0],now[1])-this.getAngle(this.startTouches[0],this.startTouches[1]); //得到旋转角度，getAngle是得到夹角的一个方法
				scale=scale.toFixed(2);
				rotation=rotation.toFixed(2);
				this.pasterRect.width=this.copyPasterRect.width*scale
				this.pasterRect.height=this.copyPasterRect.height*scale
				this.pasterCurrentOffset.left=this.copyOffset.left+(this.copyPasterRect.width-this.copyPasterRect.width*scale)/2
				this.pasterCurrentOffset.top=this.copyOffset.top+(this.copyPasterRect.height-this.copyPasterRect.height*scale)/2

				this.rotateAngle=Number(this.copyRotateAngle)+Number(rotation)

			}
		},
		onPinchEnd(e){
			if(this.isPinch){
				this.isPinch=false;
				if(this._options.autoResize){
					this.checkResize()
				}
			}
		},
		checkResize(){
			/** 拖拽放大缩小逻辑 开始 */
			//判断是否图片过小 恢复最小尺寸
			if(this._options.h==0){}
			var showW=this._options.w?this._options.w*this.materialScaleX:this.$refs.material.clientWidth
			var showH=this._options.h?this._options.h*this.materialScaleY:this.$refs.material.clientHeight
			if(this.pasterImgSize.isHorizontal&&this.pasterRect.height<showH){
				this.resetPasterRect()
			}
			if(!this.pasterImgSize.isHorizontal&&this.pasterRect.width<showW){
				this.resetPasterRect()
			}


            /** 拖拽放大缩小逻辑 结束 */
		},
        changeFlip(){
            if(this.flip==1){
                this.flip=-1
            }else{
                this.flip=1
            }
        },
		changeImg(input){
			var file = input.target.files[0];
			var reader = new FileReader();
			reader.onload=(e)=> {
				this.pasterUrl = e.target.result;
				//重置位置
				this.rotateAngle=0
				this.flip=1
				this.resetPasterRect()
			};

			//读取文件
			reader.readAsDataURL(file);
		},
		output(opt){
			var materialPosition={
				top:(this.$refs.bg.clientHeight-this.$refs.material.clientHeight)/2,
				left:(this.$refs.bg.clientWidth-this.$refs.material.clientWidth)/2,
				bottom:(this.$refs.bg.clientHeight-this.$refs.material.clientHeight)/2,
				right:(this.$refs.bg.clientWidth-this.$refs.material.clientWidth)/2,
				h:this.$refs.material.clientHeight,
				w:this.$refs.material.clientWidth
			}

			var imagePosition={
				top:materialPosition.top+this.pasterCurrentOffset.top,
				left:materialPosition.left+this.pasterCurrentOffset.left,
				bottom:this.$refs.bg.clientHeight-(materialPosition.top+this.pasterCurrentOffset.top) - this.pasterRect.height,
				right:this.$refs.bg.clientWidth-(materialPosition.left+this.pasterCurrentOffset.left) - this.pasterRect.width,
				h:this.$refs.paster.clientHeight,
				w:this.$refs.paster.clientWidth
			}

			if(opt.merge!=true&&this._options.printBorder){
				var borderW=materialPosition.w*this._options.borderRatio
				materialPosition.top-=borderW
				materialPosition.left-=borderW
				materialPosition.bottom-=borderW
				materialPosition.right-=borderW
				materialPosition.h+=borderW*2
				materialPosition.w+=borderW*2
			}
			var clipRect={
				left:materialPosition.left-imagePosition.left,
				top:materialPosition.top-imagePosition.top,
				right:materialPosition.right-imagePosition.right,
				bottom:materialPosition.bottom-imagePosition.bottom,
				leftRatio:(materialPosition.left-imagePosition.left)/imagePosition.w,
				topRatio:(materialPosition.top-imagePosition.top)/imagePosition.h,
				rightRatio:(materialPosition.right-imagePosition.right)/imagePosition.w,
				bottomRatio:(materialPosition.bottom-imagePosition.bottom)/imagePosition.h,
			}

			return this.getClipFinishImg(materialPosition ,clipRect,opt)
		},
		getClipFinishImg(materialPosition ,clipRect,opt={clipSize:null,merge:true,base64:false,encoderRatio:1}){
			var merge=opt.merge
			var clipSize=opt.clipSize
			var base64=opt.base64
			if(clipSize>3000){
				clipSize=3000
			}
			if(!opt.encoderRatio){
				opt.encoderRatio=1
			}
			return new Promise(res=>{
				var meaterial=new Image()
				meaterial.crossOrigin = "Anonymous";
				meaterial.src=this.checkImgCors(this._options.materialUrl)
				meaterial.onload=()=>{
					if(!clipSize){
						clipSize=meaterial.naturalWidth
					}
					if(!this.offcanvas1){
						this.offcanvas1=document.createElement('canvas')
					}
					var canvas=this.offcanvas1
					canvas.width=clipSize*opt.encoderRatio
					canvas.height=clipSize*(materialPosition.h/materialPosition.w)*opt.encoderRatio
					// canvas=this.setCanvasPixelRatio(canvas)
					var ctx=canvas.getContext("2d")
					console.log('ctx',ctx)
					ctx.rect(0 , 0 , canvas.width , canvas.height)
					var paster=new Image()
					paster.crossOrigin = "Anonymous";
					paster.src=this.checkImgCors(this.pasterUrl)
					paster.onload=async ()=>{
						var pasterToMaterialRatioW=this.pasterRect.width/materialPosition.w
						var scale=clipSize*opt.encoderRatio/materialPosition.w
						var outputWidth=canvas.width*pasterToMaterialRatioW
						var outputHeight=outputWidth*(this.pasterRect.height/this.pasterRect.width)
						var offsetX=clipRect.left*scale
						var offsetY=clipRect.top*scale
						//生成遮罩后的截图
						ctx.save()
						var centerPos={
							x:this.$refs.paster.clientWidth*scale/2-offsetX,
							y:this.$refs.paster.clientHeight*scale/2-offsetY,
						}

						ctx.translate(centerPos.x,centerPos.y)
						ctx.rotate(this.rotateAngle*Math.PI/180)
						ctx.scale(this.flip,1)

						ctx.drawImage(paster , 0 ,0,paster.naturalWidth,paster.naturalHeight,-centerPos.x-offsetX,-centerPos.y-offsetY,outputWidth , outputHeight)
						ctx.restore()

						var coord=this.getCoordData()


						//截图与底图拼合
						if(!this.offcanvas2){
							this.offcanvas2=document.createElement('canvas')
						}
						var canvas2=this.offcanvas2
						canvas2.width=clipSize
						canvas2.height=clipSize*(materialPosition.h/materialPosition.w)

						var ctx2=canvas2.getContext("2d")
						console.log('ctx2',ctx2)
						ctx2.rect(0 , 0 , canvas2.width , canvas2.height)
						//merge=true表示获取合成所有图层 =false表示只获取工厂需要的裁剪原图
						if(merge){
							if(this._options.materialUrl2){
								var meaterial2=new Image()
								meaterial2.crossOrigin = "Anonymous";
								meaterial2.src=this.checkImgCors(this._options.materialUrl2)
								meaterial2.onload=()=>{
									var mask=new Image()
									mask.crossOrigin = "Anonymous";
									mask.src=this.checkImgCors(this._options.coverUrl)
									mask.onload=()=>{
										//绘制底图
										ctx2.drawImage(meaterial , 0 ,0 , canvas2.width , canvas2.height)
										//绘制用户图
										ctx2.drawImage(canvas , 0 ,0 , canvas2.width , canvas2.height)
										//绘制素材图
										ctx2.drawImage(meaterial2 , 0 ,0 , canvas2.width , canvas2.height)
										//绘制遮罩图
										ctx2.drawImage(mask , 0 ,0 , canvas2.width , canvas2.height)
										if(this._options.shapeMask){
											//绘制形状遮罩
											ctx2.globalCompositeOperation="destination-in";
											var shapeMask=new Image()
											shapeMask.crossOrigin = "Anonymous";
											shapeMask.src=this.checkImgCors(this._options.shapeMask)
											shapeMask.onload=()=>{
												ctx2.drawImage(shapeMask , 0 ,0 , canvas2.width , canvas2.height)
												if(base64){
													var data=canvas2.toDataURL('image/png')
													res({data,coord})
												}else{
													canvas2.toBlob((blob)=>{
														res({blob,coord})
													},"image/png")
												}
											}

										}else{
											if(base64){
												var data=canvas2.toDataURL('image/png')
												res({data,coord})
											}else{
												canvas2.toBlob((blob)=>{
													res({blob,coord})
												},"image/png")
											}
										}

									}

								}
							}else{
								var mask=new Image()
								mask.crossOrigin = "Anonymous";
								mask.src=this.checkImgCors(this._options.coverUrl)
								mask.onload=()=>{
									console.log(1231311)
									//绘制底图
									ctx2.drawImage(meaterial , 0 ,0 , canvas2.width , canvas2.height)
									//绘制用户图
									ctx2.drawImage(canvas , 0 ,0 , canvas2.width , canvas2.height)


									if(this._options.shapeMask){
										//绘制形状遮罩
										ctx2.globalCompositeOperation="destination-in";
										var shapeMask=new Image()
										shapeMask.crossOrigin = "Anonymous";
										shapeMask.src=this.checkImgCors(this._options.shapeMask)
										shapeMask.onload=()=>{
											ctx2.drawImage(shapeMask , 0 ,0 , canvas2.width , canvas2.height)
											ctx2.globalCompositeOperation="source-over";
											//绘制遮罩图
											ctx2.drawImage(mask , 0 ,0 , canvas2.width , canvas2.height)
											if(base64){
												var data=canvas2.toDataURL('image/png')
													res({data,coord})
											}else{
												canvas2.toBlob((blob)=>{
													res({blob,coord})
												},"image/png")
											}
										}

									}else{
										//绘制遮罩图
										ctx2.drawImage(mask , 0 ,0 , canvas2.width , canvas2.height)
										if(base64){
											var data=canvas2.toDataURL('image/png')
												res({data,coord})
										}else{
											canvas2.toBlob((blob)=>{
												res({blob,coord})
											},"image/png")
										}
									}

								}
							}
						}else{
							if(this._options.materialUrl2){
								var meaterial2=new Image()
								meaterial2.crossOrigin = "Anonymous";
								meaterial2.src=this.checkImgCors(this._options.materialUrl2)
								meaterial2.onload=()=>{
									//绘制底图
									ctx2.drawImage(meaterial , 0 ,0 , canvas2.width , canvas2.height)
									//绘制用户图
									ctx2.drawImage(canvas , 0 ,0 , canvas2.width , canvas2.height)
									//绘制素材图
									ctx2.drawImage(meaterial2 , 0 ,0 , canvas2.width , canvas2.height)


									if(base64){
										var data=canvas2.toDataURL('image/png')
											res({data,coord})
									}else{
										canvas2.toBlob((blob)=>{
											res({blob,coord})
										},"image/png")
									}
								}
							}else{
								//绘制工厂图
								// ctx2.drawImage(canvas , 0 ,0 , canvas2.width , canvas2.height)
								var ratio=canvas.width/meaterial.naturalWidth

								var cropW=this._options.area.w?this._options.area.w*ratio:canvas.width
								var cropH=this._options.area.h?this._options.area.h*ratio:canvas.height

								canvas2.width=clipSize
								canvas2.height=clipSize*(cropH/cropW)

								var offsetX=this._options.area.x*ratio
								var offsetY=this._options.area.y*ratio

								console.log(cropW,cropH)
								ctx2.drawImage(canvas ,offsetX,offsetY,cropW,cropH, 0 ,0 , canvas2.width , canvas2.height)
								if(base64){
									var data=canvas2.toDataURL('image/png')
												res({data,coord})
								}else{
									canvas2.toBlob((blob)=>{
										res({blob,coord})
									},"image/png")
								}
								return
							}
						}

					}

				}
			})

		},
        getElementToPageTop(el) {
            if(el.parentElement) {
                return this.getElementToPageTop(el.parentElement) + el.offsetTop
            }
            return el.offsetTop
        },
        getElementToPageLeft(el) {
            if(el.parentElement) {
                return this.getElementToPageLeft(el.parentElement) + el.offsetLeft
            }
            return el.offsetLeft
		},
		getElementToPageBottom(el) {
            return document.body.clientHeight-el.clientHeight-this.getElementToPageTop(el)
		},
		getElementToPageRight(el) {
            return document.body.clientWidth-el.clientWidth-this.getElementToPageLeft(el)
		},

		setCanvasPixelRatio(canvas){
			canvas.style.width=canvas.width+'px'
			canvas.style.height=canvas.height+'px'
			canvas.width=canvas.width*2
			canvas.height=canvas.height*2
			return canvas
		},
		getDistance(p1, p2) {
			var x = p2.pageX - p1.pageX,
			y = p2.pageY - p1.pageY;
			return Math.sqrt((x * x) + (y * y));
		},
		getAngle(p1, p2) {
			var x = p1.pageX - p2.pageX,
			y = p1.pageY- p2.pageY;
			return Math.atan2(y, x) * 180 / Math.PI;
		},
		onBgclick(e){
			var role=e.target.getAttribute('role')
			this.pasterActive=role=='paster'
		},
		checkImgCors(url){
			if(url.startsWith('http')&&url.includes('oss')){
				return url+'?timestamp='+Date.now()
			}
			return url
		},
		getCoordData(){
			var coord={
				x:this.pasterCurrentOffset.left,
				y:this.pasterCurrentOffset.top,
				w:this.pasterRect.width,
				h:this.pasterRect.height,
				originX:this.pasterCurrentOffset.left/this.originScale,
				originY:this.pasterCurrentOffset.top/this.originScale,
				originW:this.pasterRect.width/this.originScale,
				originH:this.pasterRect.height/this.originScale,
				boxW:this.$refs.editWrap.clientWidth,
				boxH:this.$refs.editWrap.clientHeight,
				angle:this.rotateAngle,
				flip:this.flip
			}
			return coord
		},
		getImgSize(imgUrl){
			return new Promise((resolve,reject)=>{
				var img=new Image()
				img.src=imgUrl
				img.onload=()=>{
					var size={
						naturalWidth:img.naturalWidth,
						naturalHeight:img.naturalHeight,
						ratio:img.naturalWidth/img.naturalHeight,
						isHorizontal:img.naturalWidth>img.naturalHeight
					}
					resolve(size)
				}
			})

		}
    }
}
</script>
<style lang="scss">
html,body{
	margin: 0;
	padding: 0;
}
</style>
<style lang='scss' scoped>

*{
    box-sizing: border-box;
}
.editor-bg{
    position: relative;
    width: 100%;
    height: 100vh;
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 50%;
    transition: transform .5s;
    display: flex;
    justify-content: center;
    align-items: center;
    overflow: hidden;
	.bg-image{
		width: 750px;
		height: 1334px;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate3d(-50%,-50%,0);
		display: flex;
		align-items: center;
		justify-content: center;
		img{
			width: 750PX;
			height: 1334PX;
		}
	}
    .editor-main{
        width: 260PX ;
        height: 260PX ;
        position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		.wrap-left,.wrap-right{
			flex-shrink: 0;
		}
		.editor-wrap{
			position: relative;
			border-style: dashed;
			border-color: #999;
			border-width: 0;
		}
		.decorate{
			position: absolute;
			z-index: 0;
			left:50%;
			top:50%;
			transform: translate3d(-50%,-50%,0);
			background-size: 100% 100%;
		}
		.loading-wrap{
			position: absolute;
			width: 100%;
			height: 100%;
			z-index: 999;
			background: rgba($color: #fff, $alpha: 0.9);
		}
        .preview-material{
            position: absolute;
            top: 50%;
            left: 50%;
			transform: translate3d(-50%,-50%,0);
            background-position: 0 0;
            background-repeat: no-repeat;
            background-size: 100% 100%;
            pointer-events: none;
            // background-image: url();

        }
        .preview-mask{
            position: absolute;
            top: 50%;
            left: 50%;
			transform: translate3d(-50%,-50%,0);
            width: 100%;
            height: 100%;
            background-position: 0 0;
            background-repeat: no-repeat;
            background-size: 100% 100%;
			mask-size: 100% 100%;
			overflow: hidden;
			-webkit-mask-size: cover;
            .paster-img{
                position: absolute;
                width: 100%;
                height: 100%;
                left: 0;
                top: 0;
                background-size: 100%;
                background-position: 50%;
                background-repeat: no-repeat;
            }
        }
        .paster-border{
            position: absolute;
            width: calc(100% - 20px);
            height: 100%;
            // top: 0;
            // left: 10px;
            &.active{
				border: 1.5px solid #b0b0b0;
				.paster-btn-rotate,.paster-btn-flip,.paster-btn-file{
					display: block;
				}
			}
            .paster-btn-rotate{
				display: none;
                position: absolute;
                width: 40px;
                height: 40px;
                border-radius: 40px;
                right: -18px;
                bottom: -18px;
                background-repeat: no-repeat;
                background-size: 50% 50%;
                background-position: 50%;
                background-image: url();
            }
            .paster-btn-flip{
				display: none;
                position: absolute;
                width: 40px;
                height: 40px;
                border-radius: 40px;
                right: -18px;
                top: -18px;
                background-repeat: no-repeat;
                background-size: 50% 50%;
                background-position: 50%;
                background-image: url();
            }
            .paster-btn-file{
				display: none;
                position: absolute;
                width: 53px;
                height: 30px;
                border-radius: 30px;
                left: -26px;
                bottom: -15px;
                background-repeat: no-repeat;
                background-size: 70% 70%;
                background-position: 50%;
                background-image: url();
				input{
					width: 100%;
					height: 100%;
					background: chocolate;
					position: absolute;
					z-index: 99;
					opacity: 0;
				}
			}
			@media screen and (-webkit-min-device-pixel-ratio:0.5) and (min-width: 640px){
				.paster-btn-flip{
					width: 80px;
                	height: 80px;
					right: -36px;
                	top: -36px;
				}
				.paster-btn-rotate{
					width: 80px;
                	height: 80px;
					right: -36px;
                	bottom: -36px;
				}
				.paster-btn-file{
					width: 106px;
					height: 60px;
					left: -52px;
					bottom: -30px;
				}
				&.active{
					border: 3px solid #b0b0b0;
				}
			}
        }
    }
	.bottom-bar{
		position: absolute;
		left: 0;
		bottom: 0;
		z-index: 999;
		width: 100%;
	}
	.top-bar{
		position: absolute;
		left: 0;
		top: 0;
		z-index: 999;
		width: 100%;
	}
}
</style>
